package com.syezon.wifikey.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.syezon.android.base.log.FileLog;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class WifiUtil {
    public static String formatSSID(String SSID) {
        if (SSID == null) {
            SSID = "";
        }
        if (SSID.startsWith("\"") && SSID.endsWith("\"")) {
            SSID = SSID.substring(1, SSID.length() - 1);
        }
        return SSID;
    }

    /**
     * 获取当前信号SSID
     *
     * @return
     */
    public static String getWifiSSID() {
        try {
            WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo connectionInfo = wifiManager.getConnectionInfo();
            NetworkInfo connectedWifiNetInfo = getConnectedWifiNetInfo();
            if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
                return formatSSID(connectionInfo.getSSID());
            } else if (connectedWifiNetInfo != null && TextUtils.isEmpty(connectedWifiNetInfo.getExtraInfo())) {
                return formatSSID(connectedWifiNetInfo.getExtraInfo());
            }
        } catch (Exception e) {

        }

        return "";
    }

    public static WifiInfo getWifiInfo() {
        WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo;
    }

    public static NetworkInfo getConnectedWifiNetInfo() {
        //检测API是不是小于21，因为到了API23之后getNetworkInfo(int networkType)方法被弃用
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);

            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifiNetworkInfo != null && wifiNetworkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                return wifiNetworkInfo;
            }
//API大于23时使用下面的方式进行网络监听
        } else {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取所有网络连接的信息
            Network[] networks = connMgr.getAllNetworks();
            //通过循环将网络信息逐个取出来
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                        && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED
                ) {
                    return networkInfo;
                }
            }
        }

        return null;
    }

    /**
     * 获取当前信号强度级别
     *
     * @return
     */
    public static int getWifiLevel(int percent) {
        // 固定参数
        int LEVEL_NUM = 4; // 级别数
        int LEVEL_WIFI[] = {49, 74, 84, 99}; // 级别信号强度
        for (int i = 0; i < LEVEL_NUM; i++) {
            if (percent <= LEVEL_WIFI[i]) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 获取当前信号强度（原始）
     *
     * @return
     */
    public static int getWifiRssi(WifiManager wifiManager) {
        return WifiManager.calculateSignalLevel(wifiManager.getConnectionInfo().getRssi(), 80);
    }

    public static String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }


    public static boolean isWifiConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) Utils.getApp().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            return activeNetworkInfo.isConnected() && (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI);
        } else {
            return false;
        }
    }


    public static String getLockType(String capabilities) {
        String[] results = capabilities.split("\\]\\[");
        boolean wpa2 = false;
        boolean wpa = false;
        boolean ess = false;
        for (int i = 0; i < results.length; i++) {
            String result = results[i];
            if (result.contains("WPA2")) {
                wpa2 = true;
            } else if (result.contains("WPA")) {
                wpa = true;
            } else if (result.contains("ESS")) {
                ess = true;
            }
        }
        if (wpa2) {
            if (wpa) {
                return "WPA/WPA2";
            } else {
                return "WPA2";
            }
        } else {
            if (wpa) {
                return "WPA";
            } else if (ess) {
                return "open";
            }
        }
        return "";
    }


    /**
     * 禁止连接指定wifi
     *
     * @param netId
     * @return
     */
    public static boolean disableNetwork(int netId) {
        try {
            Class e = Class.forName("android.net.wifi.WifiManager$ActionListener");
            WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            Method method = WifiManager.class.getDeclaredMethod("disable", new Class[]{Integer.TYPE, e});
            method.setAccessible(true);
            Object[] args = new Object[]{Integer.valueOf(netId), null};
            method.invoke(wifiManager, args);
            return true;
        } catch (Exception var6) {
            var6.printStackTrace();
            return false;
        }
    }


    /**
     * 根据反射获取连接方法
     *
     * @param netId
     * @param wifiManager
     * @return
     */
    public static Method connectWifiByReflectMethod(int netId, WifiManager wifiManager) {
        Method connectMethod = null;
        Method[] e;
        int var4;
        int var5;
        Method methodSub;
        Class[] types;
        if (Build.VERSION.SDK_INT >= 17) {
            Log.d("SuperConnecter", "connectWifiByReflectMethod road 1 >= Android 4.2");
            e = wifiManager.getClass().getDeclaredMethods();
            var4 = e.length;

            for (var5 = 0; var5 < var4; ++var5) {
                methodSub = e[var5];
                if ("connect".equalsIgnoreCase(methodSub.getName())) {
                    types = methodSub.getParameterTypes();
                    if (types != null && types.length > 0 && "int".equalsIgnoreCase(types[0].getName())) {
                        connectMethod = methodSub;
                    }
                }
            }

            if (connectMethod != null) {
                try {
                    connectMethod.invoke(wifiManager, new Object[]{Integer.valueOf(netId), null});
                } catch (Exception var9) {
                    var9.printStackTrace();
                    Log.d("SuperConnecter", "connectWifiByReflectMethod Android " + Build.VERSION.SDK_INT + " error!");
                    return null;
                }
            }
        }
//        else if (Build.VERSION.SDK_INT == 16) {
//            Log.d("SuperConnecter", "connectWifiByReflectMethod road 2 Android 4.1");
//        }
        else {
            if (Build.VERSION.SDK_INT < 14 || Build.VERSION.SDK_INT >= 16) {
                return null;
            }

            Log.d("SuperConnecter", "connectWifiByReflectMethod road 3   4.0<= phone <4.1");
            e = wifiManager.getClass().getDeclaredMethods();
            var4 = e.length;

            for (var5 = 0; var5 < var4; ++var5) {
                methodSub = e[var5];
                if ("connectNetwork".equalsIgnoreCase(methodSub.getName())) {
                    types = methodSub.getParameterTypes();
                    if (types != null && types.length > 0 && "int".equalsIgnoreCase(types[0].getName())) {
                        connectMethod = methodSub;
                    }
                }
            }

            if (connectMethod == null) {
                try {
                    connectMethod.invoke(wifiManager, new Object[]{Integer.valueOf(netId)});
                } catch (Exception var8) {
                    var8.printStackTrace();
                    Log.d("SuperConnecter", "connectWifiByReflectMethod Android " + Build.VERSION.SDK_INT + " error!");
                    return null;
                }
            }
        }

        return connectMethod;
    }

    public static void disableAllWifiConfig() {
        WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        if (list != null) {
            Iterator var3 = list.iterator();
            while (var3.hasNext()) {
                WifiConfiguration wifiConfiguration = (WifiConfiguration) var3.next();
                disableNetwork(wifiConfiguration.networkId);
                wifiManager.disableNetwork(wifiConfiguration.networkId);
            }
        }
    }

    public static int getLockIntType(String capabilities) {
        if (!TextUtils.isEmpty(capabilities)) {
            if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                return 3;
            } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                return 2;
            } else {
                return 1;
            }
        }
        return 1;
    }


    public static WifiConfiguration CreateWifiInfo(WifiManager mWifiManager, String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        WifiConfiguration tempConfig = getWifiConfigBySsid(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if (Type == 1) //WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) //WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) //WIFICIPHER_WPA
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }


    public static WifiConfiguration getWifiConfigBySsid(String SSID) {
        WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
        if (existingConfigs != null) {
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig != null && existingConfig.SSID != null) {
                    String configSsid = formatSSID(existingConfig.SSID);
                    if (formatSSID(SSID).equals(configSsid)) {
                        return existingConfig;
                    }
                }
            }
        }

        return null;
    }


    /**
     * 获取最大priority
     *
     * @param wifiManager
     * @return
     */
    public static int getMaxPriority(WifiManager wifiManager) {
        try {
            List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
            int pri = 0;
            Iterator var3 = configurations.iterator();

            while (var3.hasNext()) {
                WifiConfiguration config = (WifiConfiguration) var3.next();
                if (config.priority > pri) {
                    pri = config.priority;
                }
            }

            return pri;
        } catch (Exception var5) {
            return 2046;
        }
    }


    /**
     * 连接配置好wifi
     */
    public static boolean connectToConfiguredNetwork(int netId) {
        WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.enableNetwork(netId, true)) {
            Method connectMethod = connectWifiByReflectMethod(netId, wifiManager);
            if (connectMethod == null) {
                return wifiManager.enableNetwork(netId, true);
            } else {
                return true;
            }
        }
        return true;
    }

    public static void disconnect() {
        WifiManager wifiManager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.disconnect();
    }


}